<template>
  <a-layout style="flex: none !important">
    <a-layout-sider
      class="layout-demo"
      collapsible
      breakpoint="xl"
      reverse-arrow
      @collapse="collapse"
    >
      <a-scrollbar
        v-show="!isCollapsed"
        style="height: 600px; overflow: auto; width: 100%"
      >
        <div class="list">
          <div style="margin-top: 20px"
            ><a-space class="head-content"
              ><div> 企业组织架构</div
              ><div
                ><a-button type="text" @click="addMainDepa()"
                  >创建部门</a-button
                ></div
              ></a-space
            >
          </div>

          <div class="content">
            <a-tree
              v-if="OrganizationData.length"
              style="background-color: white"
              :default-selected-keys="['0-0-1']"
              :fieldNames="{
                key: 'id',
                title: 'name',
              }"
              :data="OrganizationData"
              @select="getOrganization"
            >
              <template #extra="nodeData">
                <div @click="treedata(nodeData)">
                  <icon-plus
                    style="
                      position: absolute;
                      right: 28px;
                      font-size: 12px;
                      top: 10px;
                      color: #3370ff;
                    "
                  />
                </div>
                <a-popconfirm
                  content="是否确实删除?"
                  @ok="Deldepartment(nodeData.id)"
                  type="error"
                >
                  <icon-delete
                    style="
                      position: absolute;
                      right: 8px;
                      font-size: 12px;
                      top: 10px;
                      color: #3370ff;
                    "
                  />
                </a-popconfirm>
              </template>
            </a-tree>
            <a-empty v-if="!OrganizationData.length" />
            <a-modal v-model:visible="visible" @ok="handleOk">
              <template #title> 新建部门 </template>
              <a-form auto-label-width :model="form">
                <a-form-item field="name" label="部门名称">
                  <a-input v-model="form.list.name" />
                </a-form-item>
                <a-form-item field="post" label="部门编码">
                  <a-input v-model="form.list.number" />
                </a-form-item>
                <a-form-item field="post" label="上级部门">
                  <a-input disabled v-model="form.list.pName" />
                </a-form-item>
              </a-form>
            </a-modal>
          </div>
        </div>
      </a-scrollbar>
      <template #trigger="{ collapsed }">
        <IconCaretRight v-if="collapsed"></IconCaretRight>
        <IconCaretLeft v-else></IconCaretLeft>
      </template>
    </a-layout-sider>
  </a-layout>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure/index';
  import {
    addDepartment,
    delDepartment,
  } from '@/api/home/System settings/department/index';
  import { log } from 'console';
  import mitter from '@/utils/mitt';

  let router = ref();
  let data = ref();
  let arrs: any = ref([]);
  let treeDatalist = ref([]);
  const visible = ref(false);
  const bmSelectorDate = ref();
  const DepartmentSelectorDate = ref();
  const form = reactive({
    list: {
      name: '',
      pName: '',
      pid: null,
      number: '',
    },
  });
  const isCollapsed = ref(false);
  const collapse = (collapsed: boolean) => {
    isCollapsed.value = collapsed;
  };
  // 处理数据
  // function arrayToTree(list: any) {
  //   const treeData = ref([]);
  //   list.forEach((item) => {
  //     if (item.pid === 0) {
  //       treeData.value.push(item);
  //     }
  //     const children = ref([]);
  //     children.value = list.filter((data) => data.pid === item.id);
  //     if (!children.value.length) return;
  //     item.children = children.value;
  //   });
  //   return treeData;
  // }

  const fieldNames = { value: 'id', label: 'name' };

  const toTree = (list: any) => {
    // 定义最终需要返回的树形结构数据
    let treeData: any = [];
    // 对传入的数组进行遍历
    list.forEach((item: any) => {
      // 如果pid没有值,那就是顶级对象,直接添加进数组
      if (!item.pid) {
        treeData.push(item);
      }
      // 理解为二次遍历 ：每个对象都找一遍自己的孩子添加到children
      let objList = list.filter((data: any) => data.pid === item.id);
      if (objList.length) {
        item.children = objList;
      }
    });
    return treeData;
  };

  const OrganizationData = ref([]);
  const treeOrganizationchart = async () => {
    console.log('初始');
    const res = await GetOrganizationchart();
    OrganizationData.value = toTree(res.department);
    if (OrganizationData.value.length)
      mitter.emit('depaId', { id: OrganizationData.value[0].id });
  };

  const getOrganization = (key) => {
    mitter.emit('depaId', { id: key[0] });
  };

  const treedata = (value?: any) => {
    form.list.pid = value.id;
    form.list.pName = value.name;
    visible.value = true;
  };

  const Deldepartment = async (id: number) => {
    await delDepartment({ id });
    treeOrganizationchart();
  };

  // const SelectorDate = (e) => {
  //   bmSelectorDate.value = e;
  // };

  // 新增部门
  const handleOk = async () => {
    await addDepartment({
      name: form.list.name,
      pid: Number(form.list.pid),
      principal: 9,
    });
    treeOrganizationchart();
    form.list = {
      name: '',
      pName: '',
      pid: null,
      number: '',
    };
  };
  //

  // const handleOk = async () => {
  //   const { id } = DepartmentSelectorDate.value.find(
  //     (i) => i.name === bmSelectorDate.value
  //   );
  //   const { name, principal } = form;
  //   await addDepartment({ name, pid: Math.floor(id), principal: 9 });
  // };

  // const handleCancel = () => {};

  // mitter.on('msg', (value) => {
  //   getOrganizationchart();
  // });

  const addMainDepa = () => {
    form.list = {
      name: '',
      pName: '',
      pid: null,
      number: '',
    };
    visible.value = true;
  };

  onMounted(() => {
    treeOrganizationchart();
  });
</script>

<style scoped lang="less">
  .layout-demo {
    background-color: #f5f7fa;
    .scroll {
      padding: 10px;
      .search {
        background-color: #fff;
        height: 40px;
        border: 1px solid #ccc;
      }
    }
  }
  .list {
    padding: 10px;
  }
</style>

function flat(children: any) { throw new Error('Function not implemented.'); }
